<template>
  <!-- :action="`${$apiHost}/shared/upload`" -->
  <el-upload
    ref="uploader"
    :multiple="limit > 1"
    :limit="limit"
    class="uploader-wrap"
    :headers="headers"
    :action="`${$apiHost}/common/fileImgUrl`"
    :on-success="(e) => onSuccess(e, '')"
    :show-file-list="false"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <template #tip>
      <div class="img-wrap">
        <div
          class="img-item"
          v-for="(item, index) in preImgs"
          :key="index + item"
        >
          <el-image
            :src="item"
            :preview-src-list="[item]"
            fit="cover"
            class="img-item"
          >
          </el-image>
          <div class="close">
            <i class="el-icon-circle-close" @click="onRemove(index)"></i>
          </div>
        </div>
      </div>
    </template>
  </el-upload>
</template>

<script>
import { mapState } from 'vuex'
export default {
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    limit: {
      type: Number,
      default: 9,
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {}
  },
  watch: {
    value(list) {
      if (list.length <= 0) {
        const ref = this.$refs.uploader
        ref && ref.clearFiles()
      }
    },
  },
  computed: {
    ...mapState(['token']),
    preImgs() {
      return (this.value || []).map((e) => `${this.$imgHost}${e}`)
    },
    headers() {
      return {
        token: this.token || window.$quinn.getStorage('token'),
      }
    },
  },
  methods: {
    onSuccess(res) {
      const value = JSON.parse(JSON.stringify(this.value))
      if (res.code == 200 && res.result) {
        value.push(res.result[0])
        this.$emit('change', value)
      }
    },
    onRemove(index) {
      let value = JSON.parse(JSON.stringify(this.value))
      value = value.filter((e, i) => i != index)
      this.$emit('change', value)
    },
  },
}
</script>

<style lang="less" scoped></style>
